<template>
  <el-dialog
    v-el-drag-dialog
    class="dailyCenter-AddDialog"
    :title="title"
    :visible.sync="isShow"
    width="700px"
    @closed="close"
  >
    <el-steps :active="active" finish-status="success" align-center class="mb10">
      <el-step title="选择门店" />
      <el-step title="选择日期" />
      <el-step title="日结时间点" />
    </el-steps>
    <el-form
      ref="dataForm"
      class="form"
      :rules="rules"
      :model="form"
      label-position="right"
      label-width="110px"
    >
      <el-form-item v-if="active === 1" label="门店:" prop="orgId">
        <el-tree-select
          v-model="form.orgId"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择门店',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item v-else-if="active === 2" label="日结日期:" prop="date">
        <el-input
          v-model="dateText"
          placeholder="请选择日结日期"
          @focus="dateFocus"
          @blur="dateBlur"
        />
        <el-calendar v-if="isShowDate" v-model="form.date">
          <template #dateCell="{ data }">
            <template v-for="(item, index) in monthData">
              <div
                v-if="item.happendDt.slice(0, 10) === data.day"
                :key="index"
                :class="{
                  isDisabled: getIsDisabled(data.day),
                  isConfirm: item.carryStatus === 2,
                  waitConfirm: item.carryStatus === 1,
                }"
              >
                <span>{{ item.carryStatus === 1 ? "待确认" : "已确认" }}</span>
              </div>
            </template>
            <p
              :class="{
                dateText: true,
                isDisabled: getIsDisabled(data.day),
              }"
            >
              {{ data.day.split("-").slice(1).join("-") }}
            </p>
          </template>
        </el-calendar>
      </el-form-item>
      <el-form-item v-else label="日结时间点:" prop="time">
        <el-time-select
          v-model="form.time"
          :picker-options="pickerOptions"
          placeholder="选择日结时间点"
          @focus="timeFocus"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="active !== 1" type="primary" @click="previous"> 上一步 </el-button>
      <el-button type="primary" :disabled="nextStepDisabled" @click="save">
        {{ active === 3 || active === 4 ? "提交" : "下一步" }}
      </el-button>
      <el-button @click="close"> 关闭 </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    dailyStoresAddSave,
    dailyStoresInitAccount,
    dailyStoresBillByMonth,
    dailyStoresCheckSaveBill
  } from '@/api'
  import dayjs from 'dayjs'
  export default {
    props: {
      treeData: {
        type: Array
      }
    },
    data() {
      return {
        isShow: false,
        form: {
          orgId: '',
          orgSNNo: '', // 门店编号
          orgName: '', // 门店编号
          orgType: '', // 门店类型
          date: '',
          time: ''
        },
        dateText: '',
        isShowDate: false,
        rules: {
          orgId: [{ required: true, message: '请选择门店', trigger: 'change' }],
          date: [{ required: true, message: '请选择日结日期', trigger: 'change' }],
          time: [{ required: true, message: '请选择日结时间点', trigger: 'change' }]
        },
        monthData: [],
        active: 1,
        startDt: '',
        nextStepDisabled: false
      }
    },
    computed: {
      // 设置时间点选择限制
      pickerOptions() {
        const pickerOptions = {
          start: '00:00',
          step: '01:00',
          end: '23:00'
        }
        // const date = dayjs(this.form.date).format('YYYY-MM-DD')
        // const nowDate = dayjs(new Date()).format('YYYY-MM-DD')
        // const time = dayjs(new Date()).format('HH:00')
        // if (date !== nowDate) return pickerOptions
        // else {
        //   pickerOptions.end = time
        //   return pickerOptions
        // }
        return pickerOptions
      },
      title() {
        return `新增日结${':' + this.form.orgName} ${this.dateText}`
      }
    },
    watch: {
      'form.date': async function(val, oldVal) {
        // const date = dayjs(val).format('YYYY-MM-DD')
        // const newDate = dayjs(new Date()).format('YYYY-MM-DD')
        // if (val) {
        //   if (date <= newDate && date > this.startDt) this.dateText = date
        //   else {
        //     this.$message.error(
        //       `请选择门店初始设置时间${this.startDt}到${newDate}之内的时间`
        //     )
        //   }
        // }
        this.dateText = val ? dayjs(val).format('YYYY-MM-DD') : ''
        const isNewMonth = dayjs(val).get('month') !== dayjs(oldVal).get('month')
        if (this.form.orgId && isNewMonth) await this.getMonthData(val)
        if (val !== oldVal) {
          if (this.monthData.some(item => dayjs(item.happendDt).format('YYYY-MM-DD') === dayjs(val).format('YYYY-MM-DD'))) this.nextStepDisabled = true
          else this.nextStepDisabled = false
        }
      }
    },
    methods: {
      show() {
        this.isShow = true
      },
      close() {
        this.isShow = false
        this.isShowDate = false
        this.dateText = ''
        this.monthData = []
        this.active = 1
        this.form = {
          orgId: '',
          orgSNNo: '', // 门店编号
          orgName: '', // 门店编号
          orgType: '', // 门店类型
          date: '',
          time: ''
        }
        this.$refs['dataForm'].resetFields()
      },

      selectTreeChange(value) {
        this.form.orgId = value.orgId
        this.form.orgType = value.orgType
        this.form.orgName = value.orgName
        this.form.orgSNNo = value.orgSNNo
        if (this.form.date) this.getMonthData(this.form.date)
      },
      dateFocus() {
        this.isShowDate = true
        if (!this.form.date) {
          this.form.date = new Date()
          this.dateText = dayjs(this.form.date).format('YYYY-MM-DD')
        }
      },
      dateBlur() {
        this.dateText = dayjs(this.form.date).format('YYYY-MM-DD')
      },
      timeFocus() {
        this.isShowDate = false
      },
      getIsDisabled(day) {
        const newDate = dayjs(new Date()).format('YYYY-MM-DD')
        return !(day <= newDate && day > this.startDt)
      },

      // 上一步
      previous() {
        this.active--
        this.$refs['dataForm'].clearValidate()
      },
      // 下一步 提交
      save() {
        this.$refs.dataForm.validate(async(valid) => {
          if (!valid) return

          // 设置门店
          if (this.active === 1) {
            if (this.form.orgType !== 11) {
              this.$message.error('只能选择门市')
              return
            }

            const data = await this.queryInitAccount(this.form.orgId)
            if (data) {
              // 设置起始时间 只有起始时间到当前时间内的日期可以选择
              this.startDt = dayjs(data.startDt).format('YYYY-MM-DD')
            } else return
          }
          // 提交检查
          if (this.active === 2) {
            const data = await this.checkSaveBill()
            if (!data) return
          }
          // 提交
          if (this.active === 3) {
            this.saveSubmit()
            this.active++
            return
          }
          if (this.active === 4) {
            this.saveSubmit()
            return
          }
          this.active++
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 获取每月数据
      async getMonthData(time) {
        const params = {
          month: dayjs(time).format('YYYY-MM'),
          orgId: this.form.orgId
        }
        const { status, data } = await dailyStoresBillByMonth(params)
        if (status === 200) {
          this.monthData = data
        }
      },
      async saveSubmit(force) {
        let date = dayjs(this.form.date).set('hour', this.form.time.slice(0, 2))
        // date = dayjs(date).format("YYYY-MM-DD HH-00-00")
        date = dayjs(dayjs(date).format('YYYY-MM-DD HH:00:00')).toDate()
        const params = {
          orgId: this.form.orgId,
          orgSNNo: this.form.orgSNNo, // 门店编号
          orgName: this.form.orgName, // 门店名称
          happendDt: date,
          force: force || 0
        }

        const { data } = await dailyStoresAddSave(params)
        if (data.status === 200) {
          this.$notify({
            title: '提示',
            message: '提交日结成功',
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.close()
        } else if (data.status === 505) {
          this.$confirm(data.message, '提示', {
            type: 'warning'
          }).then(() => {
            this.saveSubmit(1)
          })
        }
      },
      // 查询初期门店设置
      async queryInitAccount(orgId) {
        const params = {
          orgId: orgId
        }
        const res = await dailyStoresInitAccount(params)
        if (res.success) return res
        else {
          this.$message.error('请先设置期初日期')
          return
        }
      },
      // 检查是否能新增日结
      async checkSaveBill() {
        let date = dayjs(this.form.date).set('hour', this.form.time.slice(0, 2))
        date = dayjs(dayjs(date).format('YYYY-MM-DD HH:00:00')).toDate()
        const params = {
          orgId: this.form.orgId,
          orgSNNo: this.form.orgId, // 门店编号
          orgName: this.form.orgName, // 门店名称
          happendDt: date
        }
        const { status } = await dailyStoresCheckSaveBill(params)
        return status === 200
      }
    }
  }
</script>

<style lang="scss" scoped>
.dailyCenter-AddDialog {
  .el-calendar {
    margin-top: 6px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    /deep/.el-calendar-day {
      position: relative;

      > div + p {
        color: #fff;
      }

      .dateText {
        position: absolute;
        top: 8px !important;
        left: 8px !important;
        z-index: 1;
      }

      .isDisabled {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 100%;
        height: 100%;
        pointer-events: none;
        cursor: default;
        opacity: 0.6;
      }

      @mixin call {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        padding: 19px 8px 8px 8px;
        color: #fff;
        box-sizing: border-box;
        // z-index: -1;
        // font-size: 12px;
      }

      .isConfirm {
        @include call;

        background: #399bff;
      }

      .waitConfirm {
        @include call;

        background: #ed912e;
      }
    }
    /deep/.el-calendar__body {
      padding: 4px 20px 4px;
      .el-calendar-table thead th {
        padding: 0;
      }
    }
    /deep/.el-calendar__header {
      padding: 6px 20px;
    }

    /deep/.is-selected {
      .el-calendar-day {
        .isConfirm,
        .waitConfirm,
        p {
          color: #606266;
          background-color: #f2f8fe;
        }
      }
    }
    /deep/.el-calendar-table .el-calendar-day {
      height: 46px;
      .dateText {
        height: 14px;
        line-height: 14px;
      }
    }
  }
  /deep/.el-dialog__body {
    max-height: 73vh;
    padding-bottom: 0;
  }

  .el-date-editor {
    width: 100%;
  }
}
</style>
